package btanalyzer.downloader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component("fileDownloaderImplHttpClient")
public class FileDownloaderImplHttpClient implements FileDownloader {
	
	public static final Logger log = LoggerFactory.getLogger(
			FileDownloaderImplHttpClient.class);

	/*
	 * (non-Javadoc)
	 * @see btanalyzer.downloader.FileDownloader#download(java.lang.String, java.lang.String)
	 */
	public boolean download(String url, String name) {
		
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpGet);
		} catch (Exception e) {
			log.error("error requesting url={}", url, e);
			return false;
		} 
		InputStream is = null;
		try {
			is = httpResponse.getEntity().getContent();
		} catch (Exception e) {
			log.error("error while trying to executing " +
					"httpResponse.getEntity().getContent()", e);
			return false;
		}
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(new File(name));
		} catch (FileNotFoundException e) {
			log.error("error while creating file={}", name, e);
			return false;
		}
		
		int len = 1024;
		int readed;
		try {
			for(byte[] b = new byte[len]; (readed = is.read(b)) > 0;) {
				try {
					fos.write(b, 0, readed);
				} catch (IOException e) {
					log.error("error while writing to fileOuputStream", e);
					return false;
				}
			}
		} catch (IOException e) {
			log.error("error while reading form inputStream", e);
			return false;
		}
		
		try {
			is.close();
		} catch (IOException e) {
			log.warn("error while closing inputStream", e);
		}
		try {
			fos.close();
		} catch (IOException e) {
			log.error("error while closing to fileOuputStream", e);
			return false;
		}
		
		return true;
	
	}

}
